import React, {useEffect, useMemo, useRef, useState} from "react"
import {Button, Col, Form, InputNumber, Row, Select} from "antd";
import {PlusOutlined, SearchOutlined} from "@ant-design/icons";
import {BaseSelectRef} from "rc-select";
import {GoodsSummary} from "../apis/GoodsApi";

export interface EditFormItemWithPriceRowProps<T> {
    onFinish: (values: T) => Promise<void>
    existedGoodsIds: number[]
    data: GoodsSummaryWithPrice[]
}

export interface GoodsSummaryWithPrice extends GoodsSummary{
    price:number
    rememberedPrice?:number
}

export interface EditOrderItemFormData{
    amount: number
    goodsId: string
    price:number
}

const EditOrderItemWithPriceRow = function <T extends EditOrderItemFormData>(props: EditFormItemWithPriceRowProps<T>) {
    const goodsSummaries = props.data
    const [form ]= Form.useForm()
    const defaultGoodsAmount = 1
    const [loading, setLoading] = useState(false)
    const searchGoodsRef = useRef<BaseSelectRef>(null);
    const numberInputRef = useRef<HTMLInputElement>(null);
    const priceInputRef = useRef<HTMLInputElement>(null);
    const [selectedGoodsId,setSelectedGoodsId] = useState<number>()
    const selectedGoods = useMemo(() => {
        return goodsSummaries.find(it=>it.id == selectedGoodsId)
    }, [selectedGoodsId]);
    useEffect(() => {
        if(selectedGoods){
            form.setFieldValue("price",selectedGoods.rememberedPrice??selectedGoods.price)
        }
    }, [selectedGoods]);
    return (
        <Form<T> form={form} initialValues={{
            amount: defaultGoodsAmount
        }} onFinish={(values) => {
            setLoading(true)
            props.onFinish(values).then(() => {
                form.resetFields()
                setTimeout(() => {
                    searchGoodsRef?.current?.focus()
                }, 100)
            }).finally(() => {
                setLoading(false)
            })
        }}>
            <Row style={{display: "flex", flexDirection: "row"}} gutter={16}>
                <Col span={12}>
                    <Form.Item rules={[{required: true}]} name={"goodsId"} label={"货品"}>
                        <Select style={{width: "100%"}}
                                showSearch
                                onSelect={value=>{
                                    setTimeout(()=>{
                                        numberInputRef.current?.focus()
                                        numberInputRef.current?.select()
                                    },100)
                                    setSelectedGoodsId(value)
                                }}
                                onChange={value => {
                                    setTimeout(()=>{
                                        numberInputRef.current?.focus()
                                    },100)
                                    setSelectedGoodsId(value)
                                }}
                                ref={searchGoodsRef}
                                suffixIcon={<SearchOutlined/>}
                                filterOption={(inputValue, option) => {
                                    return !!option?.label?.toLowerCase()?.includes(inputValue)
                                }}
                                placeholder={"条码、名称"}
                                options={goodsSummaries.map(it => ({
                                    label: it.barcode + "\t\t\t\t\t" + it.name + "\t\t\t\t\t" + `￥${it.price}`,
                                    value: it.id,
                                    disabled: props?.existedGoodsIds.some(item => item === it.id)
                                }))}/>
                    </Form.Item>
                </Col>
                <Col span={4}>
                    <Form.Item rules={[{required: true},{type:"number",min:0}]} name={"amount"} label={"数量"} >
                        <InputNumber ref={numberInputRef} style={{width: "100%"}} onPressEnter={() => {
                            setTimeout(() => {
                                priceInputRef?.current?.focus()
                            }, 100)
                        }}/>
                    </Form.Item>
                </Col>
                <Col span={4}>
                    <Form.Item rules={[{required: true},{type:"number",min:0}]} name={"price"} label={"零售价"} >
                        <InputNumber ref={priceInputRef} style={{width: "100%"}} onPressEnter={() => {
                            form.submit()
                        }}/>
                    </Form.Item>
                </Col>
                <Col span={4}>
                    <Button loading={loading} type={"primary"} onClick={() => {
                        form.submit()
                    }}><PlusOutlined/>添加</Button>
                </Col>
            </Row>
        </Form>
    )
}

export default EditOrderItemWithPriceRow
